from inspect import isclass, ismodule
from peewee import Model

from common.model.abstrct import AbstractModel, AbstractModelWithID


def is_model(o):
    return isclass(o) and issubclass(o, AbstractModel)


def init_table():
    from common import model
    from common.model.config.id_worker_config import IdWorkerModel
    from common.model.payment.transaction import AliPayTransaction
    from common.model.payment.pay import TenantAliPayConfig

    def hand(m):
        for i in dir(m):
            if not i.startswith("__"):
                t = getattr(m, i)
                if ismodule(t):
                    hand(t)
                else:
                    if is_model(t) and (t is not AbstractModelWithID and t is not AbstractModel and t is not Model):
                        _create_table(t)

    hand(model)


def _create_table(m):
    if m.table_exists():
        print(f"模型类:{m}已经初始化")
        return
    print(f"创建模型类:{m}")
    m.create_table(True)
    auto_increment_base = getattr(m._meta, "auto_increment_base", None)
    t_name = m._meta.table_name
    if type(auto_increment_base) == int:
        m.raw(f"alter table {t_name} auto_increment={auto_increment_base};").execute()
